package se.sll.service.catalogue.load;

import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.jms.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.cdi.CdiCamelContext;
import org.apache.camel.component.jms.JmsComponent;
import org.springframework.jms.support.destination.JndiDestinationResolver;
import se.sll.service.catalogue.common.property.CatalogProperties;
import se.sll.service.catalogue.notif.smtp.LoadSmtpCamelRoute;

/**
 *
 * @author khaleddaham
 */
@Singleton
@Startup
@Slf4j
public class BootstrapLoadCamel {

    @Inject
    CdiCamelContext camelCtx;
//    @Inject
//    LoadEICamelRoute eiCamelRoute;
    @Inject
    LoadSmtpCamelRoute smtpCamelRoute;
    
    @Resource(mappedName = CatalogProperties.JMS_CONNECTION_FACTORY)
    private ConnectionFactory camelJMSConnectionFactory;

    @PostConstruct
    public void init() throws Exception {
        log.info(">> Create CamelContext and register Camel Route.");
        
        /**
         * Add property for stax, workaround for ISSUE with Camel
         */
        Properties properties = System.getProperties();
        if( "PROPERTY_NOT_SET".equals(properties.getProperty("org.apache.cxf.stax.allowInsecureParser", "PROPERTY_NOT_SET")) ){
            log.info(">> Setting system property (workaround for ISSUE with Camel): [{} = {}]", new Object[]{"org.apache.cxf.stax.allowInsecureParser", "1"});
            properties.put("org.apache.cxf.stax.allowInsecureParser", "1");
            System.setProperties(properties);         
        }
        JmsComponent jmsComp = JmsComponent.jmsComponentAutoAcknowledge(camelJMSConnectionFactory);
        jmsComp.setDestinationResolver(new JndiDestinationResolver());
        camelCtx.addComponent("jms",jmsComp);
//        camelCtx.addRoutes(eiCamelRoute);
        
        // The route for SMTP notifications from capacity
        camelCtx.addRoutes(smtpCamelRoute);
        camelCtx.start();
        log.info(">> CamelContext created and camel route started.");
    }

    @PreDestroy
    public void stop() throws Exception {
        camelCtx.stop();
        log.info(">> CamelContext stopped.");
    }
}